package com.noah.project.global

import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken

import java.util.ArrayList

/**
 * Created by zzh on 2018/7/11.
 */

object JsonManager {
    private val gson = GsonBuilder().disableHtmlEscaping().create()

    /**
     * 返回JsonString
     */
    fun toJson(obj: Any?): String {
        try {
            if (obj != null) {
                return gson.toJson(obj)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 返回对象
     */
    fun <T> fromJson(data: String?, clazz: Class<T>): T? {
        try {
            if (data != null) {
                return gson.fromJson(data, clazz)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 返回数组对象
     */
    fun <T> fromJsonList(data: String?, clazz: Class<T>): List<T>? {
        try {
            if (data != null) {
                val type = object : TypeToken<ArrayList<JsonObject>>() {}.type
                val jsonObjects = gson.fromJson<ArrayList<JsonObject>>(data, type)
                val arrayList = ArrayList<T>()
                for (jsonObject in jsonObjects) {
                    arrayList.add(gson.fromJson(jsonObject, clazz))
                }
                return arrayList
            }
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }
        return null
    }


}
